<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">名称</label>
        <el-input v-model="query.name" clearable placeholder="名称" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">花费类型</label>
        <el-select v-model="query.spendType" clearable placeholder="类型" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery">
          <el-option
            v-for="item in dict.spend_type"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <label class="el-form-item-label">花费人</label>
        <el-input v-model="query.toPerson" clearable placeholder="花费人" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">日期数量</label>
        <el-input id="changeNum" v-model="defaulttDateNum" clearable placeholder="日期数量" style="width: 185px;" class="filter-item" @keyup.enter.native="changeNum()" />
        <el-date-picker
          v-model="query.spendTime"
          :default-time="['00:00:00', '23:59:59']"
          type="daterange"
          range-separator=":"
          size="small"
          class="date-item"
          value-format="yyyy-MM-dd HH:mm:ss"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission">

        <span slot="right">
          <div style="display: inline-block;margin: 0px 2px;">
            <el-upload
              ref="upload"
              v-permission="['admin','spend:import']"
              :show-file-list="false"
              :before-upload="beforeupload"
              :on-success="handleSuccessFile"
              :on-error="handleErrorFile"
              :action="baseApi + '/api/spend/upload'"
              :headers="headers"
              accept=".xls,.xlsx"
              enctype="multipart/form-data"
            >
              <el-button type="primary" class="filter-item" size="mini" icon="el-icon-upload">导入</el-button>
            </el-upload>
          </div>
          <el-button
            size="mini"
            class="filter-item"
            type="text"
            style="background:#fffffb;"
            @click="downloadModel"
          >
            <svg-icon icon-class="log" />
            下载模板</el-button>
        </span>

      </crudOperation>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="120px">
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" style="width: 270px;" />
          </el-form-item>
          <el-form-item label="金额" prop="price">
            <el-input v-model="form.price" style="width: 270px;" />
          </el-form-item>
          <el-form-item label="消费类型" prop="spendType">
            <el-select v-model="form.spendType" clearable filterable placeholder="请选择" style="width: 270px;">
              <el-option
                v-for="item in dict.spend_type"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <template v-if="form.spendType!==' '">

            <el-form-item label="支付类型" prop="payType">
              <el-select v-model="form.payType" filterable placeholder="请选择" style="width: 270px;">
                <el-option
                  v-for="item in dict.pay_type"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                /></el-select>
            </el-form-item>
            <el-form-item label="花费人">
              <el-input v-model="form.toPerson" style="width: 270px;" />
            </el-form-item>
            <el-form-item label="消费时间">
              <el-date-picker v-model="form.spendTime" type="datetime" style="width: 270px;" />
            </el-form-item>
            <el-form-item label="图片" style="width: 800px;">
              <el-upload
                :action="imagesUploadApi + '?name=' + form.fileName"
                list-type="picture-card"
                :limit="3"
                :on-exceed="handleExceed"
                :on-success="handleSuccess"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :before-upload="onBeforeUpload"
                :headers="headers"
                :file-list="form.pictureList"
                accept="image/jpeg,image/jpg,image/png"
              >
                <i class="el-icon-plus" />
              </el-upload>
            </el-form-item>
          </template>

        </el-form>

        <div slot="footer" class="dialog-footer">

          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="doSubmitCU()">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <div>
        <el-row>
          <!-- <Test /> -->
          <el-col :xs="4" :sm="4" :md="4" :lg="4" :xl="4">
            <div class="head-container">
              <el-tree
                :data="dataArr"
                :props="defaultProps"
                @node-click="dataChange"
              />

            </div></el-col>
          <el-col :xs="20" :sm="20" :md="20" :lg="20" :xl="20">
            <div class="param-font"><span class="label">{{ clickDate }}|总额:{{ value }}元</span></div>
            <el-table ref="table" v-loading="crud.loading" show-summary :data="crud.data" size="small" style="width: 100%;" :summary-method="getSummaries" @selection-change="crud.selectionChangeHandler">
              <el-table-column type="selection" width="55" />
              <el-table-column prop="name" label="名称" align="center" />
              <el-table-column prop="price" label="金额" align="center" />
              <el-table-column prop="spendType" label="花费类型" align="center">
                <template slot-scope="scope">
                  {{ dict.label.spend_type[scope.row.spendType] }}
                </template>
              </el-table-column>
              <el-table-column prop="payType" label="支付类型" align="center">
                <template slot-scope="scope">
                  {{ dict.label.pay_type[scope.row.payType] }}
                </template>
              </el-table-column>
              <el-table-column prop="week" label="星期" align="center" width="80">
                <template slot-scope="scope">
                  {{ getWeek(scope.row.spendTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="filePath" label="预览图" align="center" width="250">
                <template slot-scope="scope">
                  <div v-if="scope.row.filePath">
                    <el-image
                      v-for="(item) in getPicArr(scope.row.filePath)"
                      :key="item"
                      :src=" baseApi + item"
                      fit="contain"
                      :preview-src-list="[baseApi + item]"
                      lazy
                      class="el-avatar"
                    >
                      <div slot="error">
                        <i
                          class="el-icon-document"
                        />
                      </div>
                    </el-image>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="toPerson" label="花费人" align="center" />
              <el-table-column prop="spendTime" label="花费时间" align="center" :formatter="formatter" />
              <el-table-column v-if="checkPer(['admin','spend:edit','spend:del'])" label="操作" width="150px" align="center">
                <template slot-scope="scope">
                  <udOperation
                    :data="scope.row"
                    :permission="permission"
                  />
                </template>
              </el-table-column>

            </el-table>
            <pagination />
          </el-col>
        </el-row>
      </div>
      <!--分页组件-->

    </div>
  </div>
</template>

<script>

import crudSpend from '@/api/spend'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { downloadFile } from '@/utils/index'
import { download } from '@/api/data'

const defaultForm = { pictureList: [], id: null, name: null, price: null, spendType: null, payType: null, toPerson: '茹', createTime: null, spendTime: null, fileName: null, filePath: null }
export default {
  name: '',
  /* eslint-disable */
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['spend_type', 'pay_type'],
  cruds() {
    return CRUD({ title: '日常支出', url: 'api/spend', idField: 'id', sort: 'spendTime,desc', crudMethod: { ...crudSpend }})
  },
  data() {
    return {
      headers: { 'Authorization': getToken() },
      permission: {
        add: ['admin', 'spend:add'],
        edit: ['admin', 'spend:edit'],
        del: ['admin', 'spend:del']
      },
      dateNum:6,
      defaulttDateNum:null,
      rules: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '金额不能为空', trigger: 'blur' }
        ],
        spendType: [
          { required: true, message: '花费类型不能为空', trigger: 'blur' }
        ],
        payType: [
          { required: true, message: '支付类型不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'name', display_name: '名称' },
        { key: 'spendType', display_name: '消费类型' },
        { key: 'payType', display_name: '支出类型' },
        { key: 'toPerson', display_name: '花费人' }

      ],
      dataArr:[],
      dataTable:{},
      defaultProps: { children: 'children', label: 'date', isLeaf: 'leaf' },
      value:0,
      spendTypeArr:['吃','喝','玩'],
      clickDate:null,
      tableData:[],
      evenMonth:['04','06','09','11']
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'imagesUploadApi',

      'fileUploadApi'
    ])
  },
  mounted() {
    //接收路由传过来的类型
    if (this.$route.query.type) {
      if(this.spendTypeArr.includes(this.$route.query.type)) {
        this.query.spendType=this.$route.query.type
        }else{
      this.query.payType=this.$route.query.type
     }
     this.crud.toQuery()
    } else {
      this.query.spendTime = ''
    }
    //接收路由传过来的时间
   if (this.$route.query.date) {
      var month=this.$route.query.date.slice(5,7)
      var startTime=this.$route.query.date + '-01 00:00:00'
      var endTime=this.$route.query.date + '-31 00:00:00'
      if(month==='02'){
      endTime=this.$route.query.date + '-28 00:00:00'
      }
      if(this.evenMonth.includes(month)){
      endTime=this.$route.query.date + '-30 00:00:00' 
      }
      var arr=[]
      arr.push(startTime)
      arr.push(endTime)
      this.query.spendTime = arr
      this.crud.toQuery()
        } else {
      this.query.spendTime = ''
      this.query.type = ''
      }
    this.crud.toQuery()
    this.init(this.dateNum)
  },
  methods: {
    getPicArr(data){
     var arr= data.split('|')
     arr.pop()
    return arr 

    },
  [CRUD.HOOK.afterToCU](crud, form) {
      if (this.form.filePath) {
        var arr = this.form.filePath.split('|')
        for (var i = 0; i < arr.length; i++) {
          if (arr[i]) {
            var array = arr[i].split('/')
            this.form.pictureList.push({
              'url': this.baseApi + arr[i],
              response: { 'realName': array[3], 'type': array[2] }
            })
          }
        }
      }
    },
    handleSuccess(response, file, fileList) {
      console.log(file)
      this.form.filePath = ''
      for (var i = 0; i < fileList.length; i++) {
        this.form.filePath += '/file/' + fileList[i].response.type + '/' + fileList[i].response.realName + '|'
      }
    },
    // 图片上传超出最大数量
    handleExceed(file, fileList) {
      this.$message({
        message: '每条最多上传三张图片',
        center: true,
        type: 'warning'
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleRemove(file, fileList) {
      this.form.filePath = ''
      for (var i = 0; i < fileList.length; i++) {
        this.form.filePath += '/file/' + fileList[i].response.type + '/' + fileList[i].response.realName + '|'
      }
    },
    onBeforeUpload(file) {
      const isIMAGE = (file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png')
      const isLt1M = file.size / 1024 / 1024 < 100

      if (!isIMAGE) {
        this.$message.error('上传文件只能是图片格式!')
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      this.form.fileName = file.name
      return isIMAGE && isLt1M
    },
    handlePreview(file) {
      var a = this.$refs['downloadA']
      a.href = this.baseApi + '/file/' + file.response.type + '/' + file.response.realName
      a.click()
    },
    getWeek(data){
      var week;
      switch (new Date(data).getDay()) {
        case 0:
          week= '星期日'
          break
        case 1:
          week= '星期一'
          break
        case 2:
          week= '星期二'
          break
        case 3:
          week= '星期三'
          break
        case 4:
          week= '星期四'
          break
        case 5:
          week= '星期五'
          break
        case 6:
          week= '星期六'
          break
      }

      return week
      
    },
    init(dateNum){    
      crudSpend.everyMonthNum(dateNum).then(res => {
        this.dataArr = res
        // console.log(this.dataArr)
         this.value=this.dataArr[0].price
         this.clickDate=this.dataArr[0].date

      })    
      // crudSpend.getData().then(res=>{
      //   this.tableData=res
      // })
    },
    dataChange(data){
      this.clickDate=data.date
      this.value=data.price
      var startTime=data.date+'-01 00:00:00'
      var endTime=data.date+'-31 00:00:00'
      if(data.date.slice(5,7)==='02'){
      endTime=data.date + '-28 00:00:00'
      }
      if(this.evenMonth.includes(data.date.slice(5,7))){
      endTime=data.date + '-30 00:00:00' 
      }
      var arr=[]
      arr.push(startTime)
      arr.push(endTime)
      this.query.spendTime = arr
      this.crud.toQuery() 
    },
    changeNum(){
      var changeNum=document.getElementById('changeNum');
      this.dateNum=changeNum.value
      this.init(this.dateNum)
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh](form) {
      return true
    },
    beforeupload(file) {
      const isLt1M = file.size / 1024 / 1024 < 100
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      this.fileName = file.name
      return isLt1M
    },
    /** 导入模板的成功状态 */
    handleSuccessFile(res, file) {
      if (res.state === 'success') {
        this.$message({
          message: res.info,
          type: 'success'
        })
        this.crud.toQuery()
      } else {
        this.$message.error(res.message)
      }
    },
    /** 失败状态 */
    handleErrorFile(file) {
      this.$message.error('数据导入失败！')
    },
    /** 下载模板 */
    downloadModel() {
      var params = { }
      params.id = -1
      download(this.crud.url + '/export', params).then(result => {
        downloadFile(result, this.crud.title+'模板', 'xlsx')
      })
    },
   formatter(row, column, cellValue, index) {
    
      let format = 'YYYY-mm-dd'
      let date = new Date(cellValue);
      const dataItem = {
        'Y+': date.getFullYear().toString(),
        'm+': (date.getMonth() + 1).toString(),
        'd+': date.getDate().toString(),
        'H+': date.getHours().toString(),
        'M+': date.getMinutes().toString(),
        'S+': date.getSeconds().toString(),
      };
      Object.keys(dataItem).forEach((item) => {
        const ret = new RegExp(`(${item})`).exec(format);
        if (ret) {
          format = format.replace(ret[1], ret[1].length === 1 ? dataItem[item] : dataItem[item].padStart(ret[1].length, '0'));
        }
      });
      return format
    },
    
    getSummaries(param) {
        const { columns, data } = param;

        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总价';
            return;
          }
          else if(index===2){
          const values = data.map(item => Number(item[column.property]));
          // console.log(values)
          if (!values.every(value => isNaN(value))) {
            /*前一项与下一项进行累加层层递增*/
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] += ' 元';
          } }
          else {
            sums[index] = ' ';
          }
        });

        return sums;
      },
      doSubmitCU(){
        this.crud.submitCU()
        this.init(6)
      }
      }

  
}
</script>

<style scoped>

.param-font{
  position:relative;
  right: 0px;
  /* border:1px solid red */
  
}
.param-font .label{
  position: relative;
  left: 45%;
  font-size: 23px;
  /* border: 1px solid blue; */
}
</style>
